package vg.services.data_base_manager.realization;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

public class DataBaseTypeParser {
	// The string used to separator packages
  public static final String PACKAGE_SEPARATOR = ".";

	public static final String INT = "int";
	public static final String INTEGER = "integer";
	public static final String LONG = "long";
	public static final String FLOAT = "float";
	public static final String DOUBLE = "double";
	public static final String REAL = "real";
	public static final String BOOLEAN = "boolean";
	public static final String STRING = "string";
	public static final String DATE = "date";
	
	public static Class<?> string2class(String type) {
		if(type == null) return null;
		type = type.toLowerCase();
		if (type.equals(INT) || type.equals(INTEGER)) {
			return Integer.class;
		} else if (type.equals(LONG)) {
			return Long.class;
		} else if (type.equals(FLOAT)) {
			return Float.class;
		} else if (type.equals(DOUBLE) || type.equals(REAL)) {
			return Double.class;
		} else if (type.equals(BOOLEAN)) {
			return Boolean.class;
		} else if (type.equals(STRING)) {
			return String.class;
		} else if (type.equals(DATE)) {
			return Date.class;
		} else {
			return null;
		}
	}
	
  public static String class2string(Class clazz) {
    return stripPackageName(clazz.toString());
  }

  public static  Object string2object(String s, Class<?> type) throws ParseException {
		if (type == Integer.class) {
			return Integer.valueOf(s);
		} else if (type == Long.class) {
			return Long.valueOf(s);
		} else if (type == Float.class) {
			return Float.valueOf(s);
		} else if (type == Double.class) {
			return Double.valueOf(s);
		} else if (type == Boolean.class) {
			return Boolean.valueOf(s);
		} else if (type == String.class) {
			return s;
		} else if (type == Date.class) {
			return DateFormat.getInstance().parse(s);
		}
		return type.cast(s);
	}	
  /**
   * Get the short name of the specified class by striping off the package name.
   * 
   * @param classname
   *          Class name.
   * @return Short class name.
   */
  public static String stripPackageName(String classname) {
    int idx = classname.lastIndexOf(PACKAGE_SEPARATOR);

    if (idx != -1)
      return classname.substring(idx + 1, classname.length());
    return classname;
  }
}
